package com.sudo.common.component;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 主要作用：根据用户传入的Bean名称去Spring容器中查找对应的Bean
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 根据bean的名称查找bean
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据类型查找bean
     */
    public static <T> T getBean(Class<T> requireType) {
        return applicationContext.getBean(requireType);
    }

    /**
     * 根据名称和类型获取bean
     */
    public static <T> T getBean(String beanName, Class<T> requireType) {
        return applicationContext.getBean(beanName, requireType);
    }

    /**
     * 判断Spring容器中是否存在某一个bean
     */
    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    /**
     * 判断bean是否为单例
     */
    public static boolean isSingleton(String beanName) {
        return applicationContext.isSingleton(beanName);
    }

    /**
     * 根据bean的名称获取bean的类型
     */
    public static Class<?> getType(String beanName) {
        return applicationContext.getType(beanName);
    }

    /**
     * 获取接口实现类
     * @param clazz
     * @return
     */
    public static Map<String, ?> getBeansOfType(Class<?> clazz){
        return applicationContext.getBeansOfType(clazz);
    }
}
